const Storage = require('../../utils/storage')

Page({
  data: {
    keyword: '',
    showClear: false,
    // 搜索历史和热门搜索
    searchHistory: [],
    hotSearches: ['感冒发烧', '高血压', '糖尿病', '失眠', '头痛', '咳嗽', '胃病', '皮肤病'],
    // 筛选相关数据
    selectedRegion: '',
    selectedDepartment: '',
    selectedDisease: '',
    selectedSort: '',
    
    selectedRegionLabel: '',
    selectedDepartmentLabel: '',
    selectedDiseaseLabel: '',
    selectedSortLabel: '',

    regionOptions: [
      { label: '全部地区', value: '' },
      { label: '北京', value: 'beijing' },
      { label: '上海', value: 'shanghai' },
      { label: '广州', value: 'guangzhou' },
      { label: '深圳', value: 'shenzhen' }
    ],
    departmentOptions: [
      { label: '全部科室', value: '' },
      { label: '内科', value: '1' },
      { label: '外科', value: '2' },
      { label: '儿科', value: '3' },
      { label: '妇产科', value: '4' },
      { label: '眼科', value: '5' },
      { label: '口腔科', value: '6' },
      { label: '皮肤科', value: '7' },
      { label: '精神科', value: '8' }
    ],
    diseaseOptions: [
      { label: '全部疾病', value: '' },
      { label: '感冒发烧', value: '1' },
      { label: '咳嗽', value: '2' },
      { label: '头痛', value: '3' },
      { label: '失眠', value: '4' },
      { label: '胃痛', value: '5' },
      { label: '高血压', value: '6' },
      { label: '糖尿病', value: '7' },
      { label: '关节炎', value: '8' },
      { label: '皮炎', value: '9' },
      { label: '抑郁症', value: '10' }
    ],
    sortOptions: [
      { label: '综合排序', value: '' },
      { label: '评分最高', value: 'rating' },
      { label: '问诊量最多', value: 'consult' },
      { label: '价格最低', value: 'price_asc' },
      { label: '价格最高', value: 'price_desc' }
    ],
    doctors: []
  },

  onLoad(options) {
    // 获取本地存储的搜索历史
    const history = Storage.getSearchHistory();
    this.setData({
      searchHistory: history
    });

    const { departmentId, departmentName, diseaseId, diseaseName, type } = options;
    
    // 设置搜索框内容和对应的筛选值
    if (type === 'department' && departmentId && departmentName) {
      const department = this.data.departmentOptions.find(item => item.value === departmentId);
      this.setData({
        keyword: decodeURIComponent(departmentName),
        selectedDepartment: departmentId,
        selectedDepartmentLabel: department ? department.label : '',
        showClear: true
      });
    } else if (type === 'disease' && diseaseId && diseaseName) {
      const disease = this.data.diseaseOptions.find(item => item.value === diseaseId);
      this.setData({
        keyword: decodeURIComponent(diseaseName),
        selectedDisease: diseaseId,
        selectedDiseaseLabel: disease ? disease.label : '',
        showClear: true
      });
    }

    // 搜索医生
    this.searchDoctors();
  },

  onChange(e) {
    const value = e.detail.value;
    this.setData({
      keyword: value,
      showClear: !!value
    });
  },

  onClear() {
    this.setData({
      keyword: '',
      showClear: false,
      selectedRegion: '',
      selectedDepartment: '',
      selectedDisease: '',
      selectedSort: '',
      selectedRegionLabel: '',
      selectedDepartmentLabel: '',
      selectedDiseaseLabel: '',
      selectedSortLabel: ''
    }, () => {
      this.searchDoctors();
    });
  },

  onSearch() {
    if (this.data.keyword) {
      this.saveSearchHistory(this.data.keyword);
    }
    this.searchDoctors();
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    let history = this.data.searchHistory;
    // 去重
    history = history.filter(item => item !== keyword);
    // 新关键词放到最前面
    history.unshift(keyword);
    // 最多保存10条
    if (history.length > 10) {
      history = history.slice(0, 10);
    }
    this.setData({
      searchHistory: history
    });
    Storage.setSearchHistory(history);
  },

  // 清空搜索历史
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            searchHistory: []
          });
          Storage.clearSearchHistory();
          wx.showToast({
            title: '已清空',
            icon: 'success'
          });
        }
      }
    });
  },

  // 点击搜索历史
  onHistoryTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      keyword,
      showClear: true
    });
    // 显示加载中
    wx.showLoading({
      title: '搜索中...',
      mask: true
    });

    // 发起搜索请求
    wx.request({
      url: 'https://your-api-domain/api/v1/doctors/search',
      method: 'GET',
      data: {
        keyword
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          // 请求成功，展示医生列表和筛选菜单
          this.setData({
            doctors: res.data.data || [],
            selectedDepartment: res.data.departmentId || '',
            selectedDisease: res.data.diseaseId || '',
            selectedDepartmentLabel: res.data.departmentName || '',
            selectedDiseaseLabel: res.data.diseaseName || ''
          });
        } else {
          // 请求失败，使用模拟数据
          this.setMockDataAndShowList(keyword);
        }
      },
      fail: () => {
        // 请求失败，使用模拟数据
        this.setMockDataAndShowList(keyword);
      },
      complete: () => {
        // 隐藏加载中
        wx.hideLoading();
      }
    });
  },

  // 点击热门搜索
  onHotSearchTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      keyword,
      showClear: true
    });
    this.saveSearchHistory(keyword);
    
    // 显示加载中
    wx.showLoading({
      title: '搜索中...',
      mask: true
    });

    // 发起搜索请求
    wx.request({
      url: 'https://your-api-domain/api/v1/doctors/search',
      method: 'GET',
      data: {
        keyword
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          // 请求成功，展示医生列表和筛选菜单
          this.setData({
            doctors: res.data.data || [],
            selectedDepartment: res.data.departmentId || '',
            selectedDisease: res.data.diseaseId || '',
            selectedDepartmentLabel: res.data.departmentName || '',
            selectedDiseaseLabel: res.data.diseaseName || ''
          });
        } else {
          // 请求失败，使用模拟数据
          this.setMockDataAndShowList(keyword);
        }
      },
      fail: () => {
        // 请求失败，使用模拟数据
        this.setMockDataAndShowList(keyword);
      },
      complete: () => {
        // 隐藏加载中
        wx.hideLoading();
      }
    });
  },

  // 设置模拟数据并显示列表
  setMockDataAndShowList(keyword) {
    // 根据关键词判断是科室还是疾病
    const department = this.data.departmentOptions.find(
      item => item.label.includes(keyword)
    );
    const disease = this.data.diseaseOptions.find(
      item => item.label.includes(keyword)
    );

    if (department) {
      this.setData({
        selectedDepartment: department.value,
        selectedDepartmentLabel: department.label,
        selectedDisease: '',
        selectedDiseaseLabel: ''
      });
    } else if (disease) {
      this.setData({
        selectedDisease: disease.value,
        selectedDiseaseLabel: disease.label,
        selectedDepartment: '',
        selectedDepartmentLabel: ''
      });
    } else {
      // 如果都没匹配到，就只设置一个默认的科室
      this.setData({
        selectedDepartment: '1',
        selectedDepartmentLabel: '内科',
        selectedDisease: '',
        selectedDiseaseLabel: ''
      });
    }

    // 设置模拟的医生数据
    this.setData({
      doctors: [
        {
          id: 1,
          name: '张医生',
          title: '主任医师',
          hospital: '北京协和医院',
          hospitalLevel: '三甲',
          department: '内科',
          specialty: '擅长各种常见内科疾病的诊治，尤其是心血管疾病',
          avatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/doctor1.png',
          rating: '4.9',
          consultCount: '2000+',
          price: '49'
        },
        {
          id: 2,
          name: '李医生',
          title: '副主任医师',
          hospital: '北京大学第一医院',
          hospitalLevel: '三甲',
          department: '儿科',
          specialty: '小儿常见病、多发病的诊治，儿童保健',
          avatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/doctor2.png',
          rating: '4.8',
          consultCount: '1500+',
          price: '39'
        }
      ]
    });
  },

  onRegionChange(e) {
    const value = e.detail.value;
    const region = this.data.regionOptions.find(item => item.value === value);
    this.setData({
      selectedRegion: value,
      selectedRegionLabel: region ? region.label : ''
    }, () => {
      this.searchDoctors();
    });
  },

  onDepartmentChange(e) {
    const value = e.detail.value;
    const department = this.data.departmentOptions.find(item => item.value === value);
    this.setData({
      selectedDepartment: value,
      selectedDepartmentLabel: department ? department.label : '',
      selectedDisease: '', // 清空疾病选择
      selectedDiseaseLabel: ''
    }, () => {
      if (department && department.label !== '全部科室') {
        this.setData({
          keyword: department.label,
          showClear: true
        });
      }
      this.searchDoctors();
    });
  },

  onDiseaseChange(e) {
    const value = e.detail.value;
    const disease = this.data.diseaseOptions.find(item => item.value === value);
    this.setData({
      selectedDisease: value,
      selectedDiseaseLabel: disease ? disease.label : '',
      selectedDepartment: '', // 清空科室选择
      selectedDepartmentLabel: ''
    }, () => {
      if (disease && disease.label !== '全部疾病') {
        this.setData({
          keyword: disease.label,
          showClear: true
        });
      }
      this.searchDoctors();
    });
  },

  onSortChange(e) {
    const value = e.detail.value;
    const sort = this.data.sortOptions.find(item => item.value === value);
    this.setData({
      selectedSort: value,
      selectedSortLabel: sort ? sort.label : ''
    }, () => {
      this.searchDoctors();
    });
  },

  searchDoctors() {
    const { keyword, selectedRegion, selectedDepartment, selectedDisease, selectedSort } = this.data;
    
    // 显示加载中
    wx.showLoading({
      title: '搜索中...',
      mask: true
    });

    // 调用后端接口
    wx.request({
      url: 'https://your-api-domain/api/v1/doctors/search',
      method: 'GET',
      data: {
        keyword,
        region: selectedRegion,
        departmentId: selectedDepartment,
        diseaseId: selectedDisease,
        sort: selectedSort
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          this.setData({
            doctors: res.data.data || []
          });
        } else {
          wx.showToast({
            title: res.data.message || '搜索失败',
            icon: 'none'
          });
          // 使用模拟数据
          this.setMockDoctors();
        }
      },
      fail: (err) => {
        console.error('搜索失败：', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        // 使用模拟数据
        this.setMockDoctors();
      },
      complete: () => {
        // 隐藏加载中
        wx.hideLoading();
      }
    });
  },

  setMockDoctors() {
    this.setData({
      doctors: [
        {
          id: 1,
          name: '张医生',
          title: '主任医师',
          hospital: '北京协和医院',
          hospitalLevel: '三甲',
          department: '内科',
          specialty: '擅长各种常见内科疾病的诊治，尤其是心血管疾病',
          avatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/doctor1.png',
          rating: '4.9',
          consultCount: '2000+',
          price: '49'
        },
        {
          id: 2,
          name: '李医生',
          title: '副主任医师',
          hospital: '北京大学第一医院',
          hospitalLevel: '三甲',
          department: '儿科',
          specialty: '小儿常见病、多发病的诊治，儿童保健',
          avatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/doctor2.png',
          rating: '4.8',
          consultCount: '1500+',
          price: '39'
        }
      ]
    });
  },

  onDoctorTap(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/doctor/detail?id=${id}`,
      fail: (err) => {
        console.error('跳转失败：', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  }
}); 